package com.ruix.app.ui.stratum.notice;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ruix.app.R;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.ActionMapper;
import com.ruix.app.mapper.NoticeDetailMapper;
import com.ruix.app.mapper.SendCommentMapper;
import com.ruix.app.model.Comment;
import com.ruix.app.model.Notice;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.ui.adapter.NoticeDetailCommentAdapter;
import com.ruix.app.ui.adapter.NoticeDetailListAdapter;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.util.PhotoView;
import com.ruix.app.util.RoleUtil;
import com.ruix.app.util.SoftInputUtil;
import com.ruix.app.widget.CommonTitleBar;
import com.ruix.app.widget.dialog.CopyCommentDialog;
import com.ruix.app.widget.dialog.DeleteNoticeCommentDialog;
import com.ruix.app.widget.linearlistview.LinearListView;

import java.text.SimpleDateFormat;
import java.util.Date;

import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/4/21.
 */

public class NoticeRichtextDetailActivity extends BaseActivity implements View.OnClickListener ,DeleteNoticeCommentDialog.DeleteCommentListener {


    public static Intent newIntent(Context context, Notice notice) {
        Intent intent = new Intent(context, NoticeRichtextDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("notice", notice);
        intent.putExtras(bundle);
        return intent;
    }

    private Notice notice;

    private TextView noticeTitle, noticeTime, noticeForm, noticeUnconfirm, noticeContent, sendMessageView;
    private EditText leaveWordsView;
    private WebView mWebView;//,recyclerViewComments;
    private DeleteNoticeCommentDialog deleteCommentDialog;
    private CopyCommentDialog copyCommentDialog;
    private NoticeDetailCommentAdapter commentAdapter;
    private LinearListView commentsView;

    @Override
    protected int loadViewLayout() {
        return R.layout.activity_notice_rechtext_detail;

    }

    @Override
    protected void initView() {
        setTitle("通知详情");
        sendMessageView = (TextView) findViewById(R.id.tv_send_message);
        leaveWordsView = (EditText) findViewById(R.id.et_leave_words);
        mWebView = (WebView) findViewById(R.id.detail_web);

        noticeTitle = (TextView) findViewById(R.id.tv_notice_title);
        noticeTime = (TextView) findViewById(R.id.tv_notice_time);
        noticeForm = (TextView) findViewById(R.id.tv_notice_form);
        noticeUnconfirm = (TextView) findViewById(R.id.tv_notice_unconfirm);
        noticeContent = (TextView) findViewById(R.id.tv_notice_content);

        commentsView = (LinearListView) findViewById(R.id.llv_comments_details);
        commentAdapter = new NoticeDetailCommentAdapter(this);
        commentsView.setOnItemClickListener(new LinearListView.OnItemClickListener() {
            @Override
            public void onItemClick(LinearListView parent, View view, int position, long id) {
                Comment comment = notice.getComments().get(position);
                String uid = UserManager.getCurrentUser().getID();
                if (comment.getAuthorId().equals(uid)) {
                    showDeleteCommentDialog(comment, position);
                } else {
                    showCopyCommentDialog(comment.getContent());
                }
            }

            @Override
            public void onItemLongClick(LinearListView parent, View view, int position, long id) {
                Comment comment = notice.getComments().get(position);
                String uid = UserManager.getCurrentUser().getID();
                if (comment.getAuthorId().equals(uid)) {
                    showDeleteCommentDialog(comment, position);
                } else {
                    showCopyCommentDialog(comment.getContent());
                }
            }
        });
        commentsView.setAdapter(commentAdapter);

    }

    public void setWebViewHeight(final int height) {
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mWebView.getLayoutParams();//.height = height;
                layoutParams.height = height;
                mWebView.setLayoutParams(layoutParams);
            }
        });
    }


    private void initViewValue() {
        if (notice != null) {
            noticeTitle.setText(notice.getTitle());
            noticeContent.setVisibility(View.GONE);
//            noticeContent.setText(notice.getContent());

            //展示时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
            Date d1 = new Date(notice.getCeratedTime());
            String displayCreatedTime = format.format(d1);
            noticeTime.setText(displayCreatedTime);

            String roleName = RoleUtil.roleDisplayValue(notice.getRoleID());
            if (!TextUtils.isEmpty(roleName)) {
                roleName = String.format("来自于 %s", roleName);
                noticeForm.setText(roleName);
            }
            initConfirmNum(); //

            //确认通知
            String uid = UserManager.getCurrentUser().getID();
            if (!notice.getAuthorid().equals(uid)) {
                if (notice.isNeedConfirm() && !notice.isConfirmed()) {
                    CommonTitleBar titleBar = getTitleBar();
                    TextView titleBarRightBtn = titleBar.getRightBtn();
                    titleBarRightBtn.setText("确认通知");
                    titleBarRightBtn.setTextColor(getResources().getColor(R.color.green));
                    titleBarRightBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            confirmNotice();
                        }
                    });
                }
            }

            //加载数据
////            mWebView.loadData(notice.getContent(), "text/html; charset=UTF-8", null);
//            String content = String.format("<!DOCTYPE html><html><head><title>测试</title></head><body>%s</body></html>",notice.getContent());
//            mWebView.loadDataWithBaseURL("",content,"text/html","UTF-8",null);
        }
    }

    private void initConfirmNum() {
        String uid = UserManager.getCurrentUser().getID();
        if (notice.getAuthorid().equals(uid)) {
            if (notice.getMemberNum() - 1 > notice.getConfirmNum()) {
                noticeUnconfirm.setEnabled(true);
                noticeUnconfirm.setTextColor(getResources().getColor(R.color.green));
            } else {
                noticeUnconfirm.setTextColor(getResources().getColor(R.color.gray));
                noticeUnconfirm.setEnabled(false);
            }
            String cofirmCount = String.format("%d/%d确认", notice.getConfirmNum(), notice.getMemberNum());
            noticeUnconfirm.setText(cofirmCount);
            noticeUnconfirm.setVisibility(View.VISIBLE);
        } else {
            noticeUnconfirm.setVisibility(View.GONE);
        }

    }

    private void hideConfirmNoticeButtom() {
        CommonTitleBar titleBar = getTitleBar();
        TextView titleBarRightBtn = titleBar.getRightBtn();
        titleBarRightBtn.setVisibility(View.GONE);
    }

    @Override
    protected void initLocalData() {
        Intent intent = getIntent();
        if (intent != null) {
            notice = (Notice) intent.getSerializableExtra("notice");
        }
        initViewValue();
        loadNoticeDetail();
    }

    @Override
    protected void initListener() {
        leaveWordsView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    SoftInputUtil.hideSoftInput(leaveWordsView);
                    submitComment();
                    return true;
                }
                return false;
            }
        });

        leaveWordsView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    sendMessageView.setEnabled(true);
                    sendMessageView.setBackgroundResource(R.drawable.shape_login_btn_bg);
                } else {
                    sendMessageView.setEnabled(false);
                    sendMessageView.setBackgroundResource(R.drawable.shape_login_btn_bg_disable);
                }
            }
        });

        noticeUnconfirm.setOnClickListener(this);
        sendMessageView.setOnClickListener(this);

        initWebSetting();
        mWebView.getContentHeight();
    }

    private void initWebSetting() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
//        webSettings.setSupportZoom(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setLoadsImagesAutomatically(true);
//        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setDomStorageEnabled(true);
        webSettings.setBlockNetworkImage(false);
        webSettings.setTextSize(WebSettings.TextSize.LARGEST);

//        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//自适应屏幕
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.addJavascriptInterface(new JavaScriptInterface(), "HTMLOUT");
        mWebView.setWebViewClient(new WebViewClient() {

//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                return false;
//            }
//
//
//            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
//                return super.shouldOverrideUrlLoading(view,request);
//            }
//
//            public void onLoadResource(WebView view, String url) {
//            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!mWebView.getSettings().getLoadsImagesAutomatically()) {
                    mWebView.getSettings().setLoadsImagesAutomatically(true);
                }
//                mWebView.loadUrl("javascript:document.body.scrollHeight");
                //document.documentElement.scrollHeight
                // document.body.scrollHeight
                //document.body.offsetHeight
                //document.getElementsByTagName('html')[0].scrollHeight
//                mWebView.loadUrl("javascript:window.HTMLOUT.getContentHeight(document.body.offsetHeight);");

//                setWebViewHeight(view.getContentHeight()); //动态设置高度
//                mWebView.evaluateJavascript();
            }

        });

    }

    private void setH5Content(String content){
        if (!TextUtils.isEmpty(content)){
//            mWebView.loadData(notice.getContent(), "text/html; charset=UTF-8", null);
//            String contentHtml = String.format("<!DOCTYPE html><html><head><title>测试</title></head><body>%s</body></html>",content);
            mWebView.loadDataWithBaseURL("abc",content,"text/html","UTF-8",null);
        }


    }

    //确认通知
    private void confirmNotice() {
        showLoading();
        RequestFactory.confirmNotice(notice.getId(), null, new RXObserver() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object value) {
                showSuccessTip("确认成功");
                hideConfirmNoticeButtom();
                notice.setConfirmNum(notice.getConfirmNum() + 1);
                initConfirmNum();
                sendNeedupdateNotice();
                //
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }

            @Override
            public void onComplete() {
                dismissLoading();
            }
        });
    }


    public void submitComment() {
        String comment = leaveWordsView.getText().toString().trim();
        if (TextUtils.isEmpty(comment)) {
            showErrorTip("");
            return;
        }

        showLoading();
        RequestFactory.sendNoticeComment(notice.getId(), comment, new SendCommentMapper(), new RXObserver<Comment>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Comment value) {
                notice.addComment(value);
                commentAdapter.replaceAll(notice.getComments());
                leaveWordsView.setText("");
                SoftInputUtil.hideSoftInput(leaveWordsView);
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }

            @Override
            public void onComplete() {
                dismissLoading();
            }
        });

    }

    private void loadNoticeDetail() {
        RequestFactory.noticeDetail(notice.getId(), new NoticeDetailMapper(), new RXObserver<Notice>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Notice value) {
                if (value != null && value.getId().equals(notice.getId())) {
                    notice.setComments(value.getComments());
                    setH5Content(value.getContent());
                    commentAdapter.replaceAll(value.getComments());
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_notice_unconfirm:
                startActivity(ConfirmPersonActivity.newIntent(this, notice));
                break;

            case R.id.tv_send_message:
                submitComment();
                break;
        }
    }

    private void showDeleteCommentDialog(Comment comment, int commentPosition) {
        if (deleteCommentDialog == null) {
            deleteCommentDialog = new DeleteNoticeCommentDialog(this);
            deleteCommentDialog.setListener(this);
        }
        deleteCommentDialog.show(comment, commentPosition);
    }

    private void showCopyCommentDialog(String comment) {
        if (copyCommentDialog == null) {
            copyCommentDialog = new CopyCommentDialog(this);
        }
        copyCommentDialog.show(comment);
    }


    private void deleteSelfComment(Comment comment, final int position) {
        showLoading();
        RequestFactory.deleteNoticeComment(comment.getID(), new ActionMapper(), new RXObserver<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean value) {
                if (value) {
                    showSuccessTip("删除成功");
                    notice.removeCommentWithiPosition(position);
                    commentAdapter.remove(position);
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }

            @Override
            public void onComplete() {
                dismissLoading();
            }
        });

    }

    @Override
    public void deleteCommentPositive(int commentPosition) {
        Comment comment = notice.getComments().get(commentPosition);
        deleteSelfComment(comment, commentPosition);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        copyCommentDialog = null;
        deleteCommentDialog = null;
    }

    private void sendNeedupdateNotice() {
        Intent intent = new Intent();
        intent.setAction(RuiXConstant.NOTICE_UPDATE_NOTICE_LIST);
        sendOrderedBroadcast(intent, null);
    }

    class JavaScriptInterface {

        @JavascriptInterface
        public void getContentHeight(String value) {
            if (value != null) {
                int webviewContentHeight = Integer.parseInt(value) + 20;
//                setWebViewHeight(webviewContentHeight);
            }
        }
    }
}
